package lx.scrmXj;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import lx.util.DateUtil;
import lx.util.HttpHelper;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

/**
 * @Description: 部门信息同步
 * @Author: 李星 lixing_java@163.com
 * @Date: 2020/3/27 15:06
 */
public class DepartmentTask extends TimerTask {

    @Override
    public void run() {
        try {
            departmentTask();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 查询通讯录token
    public String getToken() throws Exception {
        String tokenUrl = "SELECT ACCESS_TOKEN FROM XJ_SCRM_TOKEN where CATEGORY = 1 ORDER BY CREATE_TIME DESC";
        List<Record> recordTokenList = Db.find(tokenUrl);
        String token = recordTokenList.get(0).getStr("ACCESS_TOKEN");
//        System.out.println(MessageFormat.format("{0} 部门信息同步获取token：{1}", DateUtil.dateToDateTimeCharacter(new Date()), token));
        return token;
    }

    // 同步部门信息
    public void departmentTask() throws Exception {
        JSONArray departmentArray;
        try {
            // TODO 获取部门列表
            String departmentRes = HttpHelper.sendRequestHttps(
                    MessageFormat.format("https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={0}", getToken()),
                    "GET",
                    null);
            JSONObject departmentJson = JSONObject.parseObject(departmentRes);
            if (0 == departmentJson.getInteger("errcode") && "ok".equals(departmentJson.getString("errmsg"))) {
                // 部门信息列表
                departmentArray = departmentJson.getJSONArray("department");
//                System.out.println(MessageFormat.format("{0} 获取部门列表成功：{1}", DateUtil.dateToDateTimeCharacter(new Date()), departmentArray.size()));
                // 查询当前本地部门信息条数
                Long localDepartmentCount = Db.queryLong("SELECT COUNT(ID) FROM XJ_SCRM_DEPARTMENT");
//                System.out.println(MessageFormat.format("{0} 本地部门信息数据：{1}", DateUtil.dateToDateTimeCharacter(new Date()), localDepartmentCount));
                // 循环添加部门信息（部门数量比较大的情况下建议开启多线程）
                for (int i = 0; i < departmentArray.size(); i++) {
                    insertDepartment(localDepartmentCount, departmentArray.getJSONObject(i), i);
                }
            } else {
                System.out.println(MessageFormat.format("{0} 获取部门列表失败：{1}", DateUtil.dateToDateTimeCharacter(new Date()), departmentRes));
            }
        } catch (Exception e) {
            System.out.println(MessageFormat.format("{0} 获取部门列表出错：{1}", DateUtil.dateToDateTimeCharacter(new Date()), e.getMessage()));
        }
    }

    // 添加部门信息
    public void insertDepartment(long localDepartmentCount, JSONObject department, int index) throws Exception {
        try {
            Record departmentRecord = new Record();
            departmentRecord.set("ID", department.getInteger("id")); // 编号
            departmentRecord.set("PARENTID", department.getInteger("parentid")); // 上级编号
            departmentRecord.set("\"ORDER\"", department.getInteger("order")); // 在父部门中的次序值。order值大的排序靠前
            departmentRecord.set("NAME", department.getString("name")); // 部门名称
            departmentRecord.set("NAME_EN", department.getString("name_en")); //
            //
            String operateFlag;
            boolean resultFlag = true;
            if (localDepartmentCount == 0) {
                // TODO 本地部门信息为空，发起添加
                operateFlag = "insert";
                resultFlag = Db.save("XJ_SCRM_DEPARTMENT", "ID", departmentRecord);
            } else {
                // 根据部门编号查询本地部门信息
                Record departmentRecordForSelect = Db.findFirst("SELECT * FROM XJ_SCRM_DEPARTMENT WHERE ID = ?", departmentRecord.getInt("ID"));
                if (departmentRecordForSelect == null) {
                    // TODO 当前部门信息不存在，发起添加
                    operateFlag = "insert";
                    resultFlag = Db.save("XJ_SCRM_DEPARTMENT", "ID", departmentRecord);
                } else {
                    // TODO 当前部门信息已经存在，发起更新
                    operateFlag = "update";
                    // resultFlag = Db.update("XJ_SCRM_DEPARTMENT", "ID", departmentRecord); // 如果是迭代递增的需求，则次处开启
                }
            }
            System.out.println(MessageFormat.format("{0} 第{1}条 部门[id={2},name={3}] {4}结果：{5}",
                    DateUtil.dateToDateTimeCharacter(new Date()),
                    index+1,
                    departmentRecord.getInt("ID"),
                    departmentRecord.getStr("NAME"),
                    operateFlag,
                    resultFlag));
            System.out.println();
        } catch (Exception e) {
            System.out.println(MessageFormat.format("{0} 第{1}条 添加部门信息（{2}）出错：{3}",
                    DateUtil.dateToDateTimeCharacter(new Date()),
                    index+1,
                    JSONObject.toJSONString(department),
                    e.getMessage()));
        }
    }

}
